package com.cloud.common.utils;

import com.cloud.common.exception.CloudException;
import com.cloud.common.exception.enums.ErrorEnum;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Arrays;
import java.util.Set;

/**
 * 基于JSR303的参数校验框架工具
 *
 * @author wangjian
 * @version 1.0.0
 * @create 2020年10月27日 11:33
 * @since JDK 1.8
 * Life is so short,do something to make yourself happy,such as coding
 */
public class ValidatorUtil {

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory()
            .getValidator();

    public static void validate(Object obj) throws CloudException {
        Set<ConstraintViolation<Object>> set = VALIDATOR.validate(obj, Default.class);
        if (set != null && set.size() > 0) {
            for (ConstraintViolation<Object> cv : set) {
                throw new CloudException(ErrorEnum.PARAM_ERROR, cv.getPropertyPath().toString() + ": " + cv.getMessage());
            }
        }
    }

    public static void validate(Object obj, String... propertys) throws CloudException {
        int length = 0;
        if (propertys != null && (length = propertys.length) > 0) {
            Arrays.asList(propertys).forEach(property -> {
                Set<ConstraintViolation<Object>> set = VALIDATOR.validateProperty(obj, property, Default.class);
                if (set != null && set.size() > 0) {
                    for (ConstraintViolation<Object> cv : set) {
                        throw new CloudException(ErrorEnum.PARAM_ERROR, cv.getPropertyPath().toString() + ": " + cv.getMessage());
                    }
                }
            });
        }
    }

}
